package org.JWCB.judge.callback;

import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Statistics;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;


@Slf4j
@Getter
@Setter

public class StatisticsCallback implements ResultCallback<Statistics> {

    private Long maxMemory = 0L;
    private final CountDownLatch firstDataLatch = new CountDownLatch(1); // 同步锁
    private volatile boolean hasData = false;
    private Closeable closeable;
    @Override
    public void onNext(Statistics statistics) {
        log.info("=============接收到新的统计信息{}", statistics.getMemoryStats().getMaxUsage());
        Long usage = statistics.getMemoryStats().getMaxUsage();
        if (usage != null && usage > 0) {
            maxMemory = Math.max(usage, maxMemory);
            if (!hasData) { // 第一次数据到达时释放锁
                hasData = true;
                firstDataLatch.countDown();
            }
        }
    }

    public void awaitFirstData(long timeout, TimeUnit unit)
            throws InterruptedException {
        firstDataLatch.await(timeout, unit);
    }
    @Override
    public void onStart(Closeable closeable) {
        this.closeable = closeable;
    }

    @Override
    public void onComplete() {
    }


    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void close() throws IOException {
        if(this.closeable != null) {
            this.closeable.close();
        }
    }
}
